<template>
  <div class="app-container" :loading="loading">
    <vxe-form
      :data="formData"
      @submit="onSearchBtnClick"
      @reset="onSearchBtnClick"
    >
      <vxe-form-item
        field="name"
        :item-render="{
          name: 'input',
          attrs: { placeholder: '请输入角色名称' },
        }"
      />
      <vxe-form-item
        :item-render="{
          name: '$buttons',
          children: [
            {
              props: {
                type: 'submit',
                content: 'common.select',
                status: 'primary',
              },
            },
            {
              props: { type: 'reset', content: 'common.reset' },
            },
          ],
        }"
      />
    </vxe-form>
    <vxe-toolbar :refresh="{ query: onSearchBtnClick }">
      <template v-slot:buttons>
        <vxe-button
          v-auth="['admin', 'role:add']"
          size="medium"
          icon="el-icon-circle-plus-outline"
          status="primary"
          @click="onAddBtnClick"
          >新增</vxe-button
        >
        <vxe-button
          v-auth="['admin', 'role:delete']"
          size="medium"
          icon="el-icon-delete"
          status="danger"
          :disabled="!multipleSelection.length"
          @click="onDeleteBtnClick"
          >删除</vxe-button
        >
      </template>
    </vxe-toolbar>
    <el-row :gutter="15">
      <el-col
        :xs="24"
        :sm="24"
        :md="18"
        :lg="18"
        :xl="20"
        style="margin-bottom: 10px"
      >
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <vxe-table
            ref="table"
            border
            resizable
            size="mini"
            :loading="loading"
            highlight-current-row
            :data="tableData"
            @checkbox-all="selectAllEvent"
            @checkbox-change="selectChangeEvent"
            @cell-click="onTableclick"
            align="left"
            show-overflow
            show-header-overflow
          >
            <vxe-table-column type="checkbox" width="50" />
            <vxe-table-column field="name" title="角色名称" width="150px" />
            <vxe-table-column field="description" title="描述" width="150px" />
            <vxe-table-column
              field="createTime"
              title="创建时间"
              width="150px"
            />
            <vxe-table-column
              title="操作"
              width="100"
              align="center"
              fixed="right"
            >
              <template v-slot="{ row }">
                <el-tooltip content="编辑" placement="bottom" effect="light">
                  <vxe-button
                    v-auth="['admin', 'role:update']"
                    size="mini"
                    icon="el-icon-edit"
                    status="primary"
                    @click="onEditBtnClick(row)"
                  />
                </el-tooltip>
              </template>
            </vxe-table-column>
          </vxe-table>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="4">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <vxe-button
              v-auth="['admin', 'role:update']"
              icon="el-icon-check"
              size="small"
              style="float: right"
              status="primary"
              @click="getCheckedNodes"
              >保存</vxe-button
            >
          </div>
          <el-tree
            ref="keys"
            :data="data"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            :default-checked-keys="checked"
          />
        </el-card>
      </el-col>
    </el-row>
    <vxe-pager
      :current-page.sync="formData.currentPage"
      :page-size.sync="formData.pageSize"
      :total="total"
      :page-sizes="[10, 20, 100, 200]"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total',
      ]"
      @page-change="handlePageChange"
    />
    <Form v-if="detail" v-model="detail" />
  </div>
</template>
<script>
import { roles, del } from '@/api/role'
import { menus, tree, merge } from '@/api/menu'
import Form from './form'
export default {
  components: {
    Form,
  },
  data() {
    return {
      loading: false,
      formData: {
        currentPage: 1,
        pageSize: 20,
      },
      tableData: [],
      multipleSelection: [],
      detail: null,
      total: 0,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      param: {},
      checked: [],
      roleId: '',
    }
  },
  created() {
    this.onSearchBtnClick()
    this.onTreeBtnClick()
  },
  methods: {
    getCheckedNodes() {
      const treeKeys = this.$refs.keys
        .getCheckedKeys()
        .concat(this.$refs.keys.getHalfCheckedKeys())
      if (this.roleId) {
        this.loading = true
        merge(this.roleId, treeKeys).then(data => {
          this.$notify({
            type: 'success',
            message: '更新成功',
          })
          this.loading = false
        })
      } else {
        this.$notify({
          type: 'error',
          message: '请先选中角色',
        })
      }
    },
    selectAllEvent({ checked, records }) {
      this.multipleSelection = records
    },
    selectChangeEvent({ checked, records }) {
      this.multipleSelection = records
    },
    onTableclick(row) {
      this.roleId = row.data[row.rowIndex].id
      tree(this.roleId).then(data => {
        this.$refs.keys.setCheckedKeys([])
        this.checked = data
      })
    },
    onAddBtnClick() {
      this.detail = {}
    },
    onEditBtnClick(row) {
      this.detail = row
    },
    onSearchBtnClick() {
      this.loading = true
      roles(this.formData).then(data => {
        this.tableData = data.list
        this.total = data.total
        this.loading = false
        this.$refs.keys.setCheckedKeys([])
        this.roleId = ''
      })
    },
    onTreeBtnClick() {
      menus(this.param).then(data => {
        this.data = data
      })
    },
    onDeleteBtnClick() {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => this.deleteData())
    },
    async deleteData() {
      const selectRecords = this.$refs.table.getCheckboxRecords()
      await del(selectRecords.map(item => item.id))
      this.$notify({
        type: 'success',
        message: '删除成功!',
      })
      this.onSearchBtnClick()
    },
    handlePageChange({ currentPage, pageSize }) {
      this.formData.currentPage = currentPage
      this.formData.pageSize = pageSize
      this.onSearchBtnClick()
    },
  },
}
</script>
